package com.qf.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.qf.blog.commons.constant.RedisKeys;
import com.qf.blog.dto.TokenDto;
import com.qf.blog.entity.User;
import com.qf.blog.service.UserTokenService;
import com.qf.commons.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * User: key
 * ClassName:UserTokenServiceImpl
 * Date: 2023/6/7
 * Time: 16:42
 * description:
 */
@Service
public class UserTokenServiceImpl implements UserTokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UUIDUtils utils;
    @Override
    public TokenDto create(User user) {
        TokenDto tokenDto = new TokenDto();
        tokenDto.setUsername(user.getUsername());
        tokenDto.setUserId(user.getId());
        tokenDto.setCreateTime(new Date());
        tokenDto.setUuid(utils.getId());
        tokenDto.setHeaderUrl(user.getHeaderUrl());
        String key = String.format(RedisKeys.USER_LOGIN_TOKEN_KEY,tokenDto.getUuid());
        String value = JSON.toJSONString(tokenDto);
        stringRedisTemplate.opsForValue().set(key,value,30, TimeUnit.MINUTES);
        return tokenDto;
    }

    @Override
    public TokenDto getUser(String uuid) {
        String key = String.format(RedisKeys.USER_LOGIN_TOKEN_KEY, uuid);
        String json = stringRedisTemplate.opsForValue().get(key);
        if (!ObjectUtils.isEmpty(json)) {
            return JSON.parseObject(json, TokenDto.class);
        }
        return null;
    }
}
